import std.random;
import std.stdio: writefln;
import std.math: abs;

public class Perceptron {
	int theta;
	int[] wagi;
	bool trained = false;

	int bestAge = 0;
	private int currAge = 0;
	private int[] bestWagi;

	this(int size){
		wagi.length = size;
		for(int i = 0; i < size; i++)
			while(!wagi[i])
				wagi[i] = (rand() % 10) - 5;
		theta = (rand() % 10) - 5;
		bestWagi.length = size;
	}
	
	int detect(int[] input){
		int val = 0;
		for(int i = 0; i < input.length; i++)
			val += wagi[i] * input[i];
		
		if(val > theta) return 1;
		else if(val < theta) return -1;
		else return 0;
	}


	void train(int[] input, int expect){
			
		int eval = detect(input);
		if(eval != expect){
			currAge = 0;
			theta -= expect;
			foreach(a,inout b; wagi)
				 b += (input[a] * expect);
		}
		else{
			currAge++;
			if(currAge > bestAge){
				bestAge = currAge;
				bestWagi[] = wagi[];
			}
		}
	}

	void endTraining(){
		writefln(bestAge);
		trained = true;
		wagi[] = bestWagi[];
		writefln(theta,": ",wagi);
	}

	int key(int res, int[] input){
		int key = -1;
		int maxW = -1;
		foreach(int i,inout w; wagi)
			if(w*input[i]*res > 0 && abs(w) > maxW){
				key = i;
				maxW = w;
			}
/+		if(key > -1){
			theta -= input[key] * wagi[key];
			wagi[key] = 0;
		}+/
		return key;
	}

	void delKey(int k, int[] input){
		theta -= input[k] * wagi[k];
		wagi[k] = 0;
	}

	bool mainKey(int k){
		int sum = 0;
		foreach(int i, w;wagi)
			if(i != k)
				sum += abs(w);
		sum -= theta;
		if(wagi[k] > sum)
			return true;
		else
			return false;
	}
}
